package com.key.w8.http1.connection.reconnect.connectionImpl;

import com.key.w8.http1.connection.ChannelBuilder;
import com.key.w8.http1.connection.connectionImpl.ClientHttp1PersistentConnection;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.EventLoopGroup;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: k8
 * @CreateTime: 2025-03-22
 * @Version: 1.0
 */
public class ClientReconnectSupportConnection extends ClientHttp1PersistentConnection {
    private final EventLoopGroup group;
    private final ChannelBuilder channelBuilder;
    private final int reConnectTimes;
    public ClientReconnectSupportConnection(long responseTimeOut, TimeUnit responseTimeUnit, int reConnectTimes, int maxRequestSends, EventLoopGroup group,ChannelBuilder channelBuilder) {
        super(responseTimeOut, responseTimeUnit, maxRequestSends);
        this.channelBuilder = channelBuilder;
        this.group = group;
        this.reConnectTimes = reConnectTimes;
    }

    public ClientReconnectSupportConnection(long responseTimeOut, TimeUnit responseTimeUnit,int reConnectTimes, EventLoopGroup group,ChannelBuilder channelBuilder) {
        super(responseTimeOut, responseTimeUnit);
        this.channelBuilder = channelBuilder;
        this.group = group;
        this.reConnectTimes = reConnectTimes;
    }

    @Override
    public void tryClose() throws IOException {
        try {
            super.reconnectLock.lock();
            Bootstrap bootstrap = channelBuilder.doBuildStrap(group, this);
            channelBuilder.doConnect(bootstrap,this,new AtomicInteger(reConnectTimes));
        }finally {
            super.reconnectLock.unlock();
        }
    }
}
